import json
from datetime import datetime

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View

from field.models import *


# Create your views here.
# 查询所有数据
class ListView(View):
    def get(self, req):
        obj_list = Address.objects.all().values()  # .values() 转成字典

        select_data = []
        unique_cities = list(set(item['city'] for item in obj_list))

        for city in unique_cities:
            city_data = [item for item in obj_list if item['city'] == city]
            children = []
            for address in city_data:
                children.append({'value': address['id'], 'label': address['name']})
            select_data.append({'value': city_data[0]['id'], 'label': city_data[0]['city'], 'children': children})

        return JsonResponse({'code': 200, 'data': list(obj_list), 'select_data': list(select_data)})  # 把外层的容器转为List后返回


# 信息查询
class SearchView(View):
    def post(self, req):
        data = json.loads(req.body.decode('utf-8'))
        pageNum = data['pageNum']  # 当前页
        pageSize = data['pageSize']  # 每页大小
        query = data['query']  # 查询参数
        dataPage = Paginator(Address.objects.filter(name__icontains=query), pageSize).page(pageNum)
        # data = list(dataPage.object_list.values())  # 先转成字典，再转成列表

        # 序列化数据 - 传递查询集给序列化器
        serializer = AddressSerializer(dataPage.object_list, many=True)
        total = Address.objects.filter(name__icontains=query).count()
        return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})


class ActionView(View):
    # 根据id获取信息
    def get(self, req):
        obj = Address.objects.get(id=req.GET.get('id'))
        return JsonResponse({'code': 200, 'data': AddressSerializer(obj).data})

    def delete(self, request):
        """
        删除操作
        :param request:
        :return:
        """
        idList = json.loads(request.body.decode("utf-8"))
        Address.objects.filter(id__in=idList).delete()
        return JsonResponse({'code': 200, 'msg': '执行成功！'})


# 新增或修改
class SaveView(View):
    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        if data['id'] == -1:  # 添加
            try:
                if Address.objects.get(name=data['name']):
                    return JsonResponse({'code': 500, 'msg': '已经存在相同名称的样地！'})
            except Address.DoesNotExist:
                pass  # 没有找到则继续后续逻辑

            obj = Address(province=data['province'], city=data['city'], county=data['county'], town=data['town'],
                          name=data['name'])
            obj.create_time = datetime.now().date()
            obj.save()
        else:  # 修改
            obj = Address(id=data['id'], province=data['province'], city=data['city'], county=data['county'],
                          town=data['town'], name=data['name'], detail=data['detail'])
            obj.update_time = datetime.now().date()
            obj.save()
        return JsonResponse({'code': 200, 'msg': '执行成功！'})
